#include "orderstatuswidget.h"
#include "ui_orderstatuswidget.h"
#include "DatabaseManager.h"
#include "paymentwidget.h"

#include<QPainter>

// ProductItemWidget 类的实现
ProductItemWidget::ProductItemWidget(QWidget *parent) :
    QWidget(parent),
    m_networkManager(new QNetworkAccessManager(this))
{
    // 创建布局和控件
    // ProductItemWidget 构造函数中修改布局
    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(5, 5, 5, 5);
    layout->setSpacing(10);

    m_imageLabel = new QLabel(this);
    m_imageLabel->setFixedSize(60, 60);
    m_imageLabel->setStyleSheet("border: 1px solid #ddd; background-color: #f9f9f9;");
    m_imageLabel->setAlignment(Qt::AlignCenter);

    m_nameLabel = new QLabel(this);
    m_nameLabel->setWordWrap(true);
    m_nameLabel->setMinimumWidth(200);

    m_priceLabel = new QLabel(this);
    m_priceLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    m_quantityLabel = new QLabel(this);
    m_quantityLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    // 添加到布局
    layout->addWidget(m_imageLabel);
    layout->addWidget(m_nameLabel, 3);
    layout->addWidget(m_priceLabel, 1);
    layout->addWidget(m_quantityLabel, 1);

    setLayout(layout);
}

ProductItemWidget::~ProductItemWidget()
{

}

// orderStatusWidget 类的实现
orderStatusWidget::orderStatusWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::orderStatusWidget),
    m_networkManager(new QNetworkAccessManager(this))
{
    ui->setupUi(this);
    setWindowTitle("订单详情");
    resize(800, 800);

    // 应用整体样式表
        setStyleSheet( R"(
            orderStatusWidget {
                background-color: #f5f7fa;
                font-family: 'Segoe UI', 'Microsoft YaHei';
            }

            QGroupBox {
                background-color: white;
                border-radius: 8px;
                border: 1px solid #dcdfe6;
                margin-top: 1.5ex;
                font-weight: bold;
                color: #303133;
            }

            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                background-color: white;
            }

            QLabel {
                color: #606266;
                font-size: 14px;
            }

            QPushButton {
                background-color: #409eff;
                color: white;
                border-radius: 4px;
                padding: 8px 16px;
                font-size: 14px;
                border: none;
                min-width: 80px;
            }

            QPushButton:hover {
                background-color: #66b1ff;
            }

            QPushButton:pressed {
                background-color: #3a8ee6;
            }

            QPushButton#cancelOrderButton {
                background-color: #f56c6c;
            }

            QPushButton#cancelOrderButton:hover {
                background-color: #f78989;
            }

            QPushButton#confirmReceiptButton {
                background-color: #67c23a;
            }

            QPushButton#confirmReceiptButton:hover {
                background-color: #85ce61;
            }

            QScrollArea {
                border: none;
                background: transparent;
            }

            QScrollBar:vertical {
                width: 8px;
                background: #ebeef5;
            }

            QScrollBar::handle:vertical {
                background: #c0c4cc;
                border-radius: 4px;
                min-height: 30px;
            }

            QScrollBar::handle:vertical:hover {
                background: #a0a4ac;
            }
        )" );
                // 设置订单信息样式
                    ui->orderIdLabel->setStyleSheet("font-weight: bold; color: #303133;");
                    ui->orderTimeLabel->setStyleSheet("color: #909399;");
                    ui->statusLabel->setStyleSheet("font-weight: bold; color: #e6a23c;");
                    ui->paymentMethodLabel->setStyleSheet("color: #909399;");

                    // 设置收货信息样式
                    ui->recipientLabel->setStyleSheet("font-weight: bold; color: #303133;");
                    //ui->phoneLabel->setStyleSheet("color: #606266;");
                    ui->addressLabel->setStyleSheet("color: #606266;");

                    // 设置价格信息样式
                    ui->subtotalLabel->setStyleSheet("color: #606266;");
                    ui->shippingFeeLabel->setStyleSheet("color: #606266;");
                    ui->discountLabel->setStyleSheet("color: #f56c6c;");
                    ui->totalLabel->setStyleSheet("font-weight: bold; font-size: 16px; color: #303133;");

                    //添加分割线增强视觉效果
                    //addSeparators();
                    // 设置按钮对象名用于样式表
                       ui->paymentButton->setObjectName("paymentButton");
                       ui->cancelOrderButton->setObjectName("cancelOrderButton");
                       ui->confirmReceiptButton->setObjectName("confirmReceiptButton");
                       ui->trackButton->setObjectName("trackButton");



    // 使用UI文件中的容器和布局
    ui->productsScrollArea->setWidgetResizable(true);
    ui->productsScrollArea->setWidget(ui->productsContainer);

    // 在 orderStatusWidget 构造函数中初始化滚动区布局
    ui->productsContainer->setLayout(ui->productsLayout); // 确保 productsLayout 是 QVBoxLayout
    ui->productsScrollArea->setWidget(ui->productsContainer);
    ui->productsScrollArea->setWidgetResizable(true); // 开启滚动区自适应

    // 设置按钮样式
    ui->paymentButton->setStyleSheet("QPushButton {"
                                     "   background-color: #4CAF50;"
                                     "   color: white;"
                                     "   border-radius: 4px;"
                                     "   padding: 6px 12px;"
                                     "   font-weight: bold;"
                                     "}"
                                     "QPushButton:hover {"
                                     "   background-color: #45a049;"
                                     "}");

    ui->trackButton->setStyleSheet("QPushButton {"
                                   "   background-color: #2196F3;"
                                   "   color: white;"
                                   "   border-radius: 4px;"
                                   "   padding: 6px 12px;"
                                   "   font-weight: bold;"
                                   "}"
                                   "QPushButton:hover {"
                                   "   background-color: #0b7dda;"
                                   "}");

    ui->confirmReceiptButton->setStyleSheet("QPushButton {"
                                            "   background-color: #ff9800;"
                                            "   color: white;"
                                            "   border-radius: 4px;"
                                            "   padding: 6px 12px;"
                                            "   font-weight: bold;"
                                            "}"
                                            "QPushButton:hover {"
                                            "   background-color: #e68a00;"
                                            "}");

    ui->cancelOrderButton->setStyleSheet("QPushButton {"
                                       "   background-color: #f44336;"
                                       "   color: white;"
                                       "   border-radius: 4px;"
                                       "   padding: 6px 12px;"
                                       "   font-weight: bold;"
                                       "}"
                                       "QPushButton:hover {"
                                       "   background-color: #d32f2f;"
                                       "}");

}

orderStatusWidget::~orderStatusWidget()
{
    delete ui;
}

// 订单信息
void orderStatusWidget::setOrderInfo(const QString &orderId,
                               const QDateTime &orderTime,
                               const QString &status,
                               const QString &paymentMethod)
{
    m_orderId = orderId;
    ui->orderIdLabel->setText("订单编号: " + orderId);
    ui->orderTimeLabel->setText("下单时间:" + orderTime.toString("yyyy-MM-dd hh:mm:ss"));
    ui->statusLabel->setText("订单状态:" + status);
   // ui->paymentMethodLabel->setText("支付方式:" + paymentMethod);

    // 根据订单状态设置按钮可见性和样式
    if (status == "待支付") {
        ui->paymentButton->setVisible(true);
        ui->trackButton->setVisible(false);
        ui->confirmReceiptButton->setVisible(false);
        ui->cancelOrderButton->setVisible(true); // 可以取消订单
        ui->statusLabel->setStyleSheet("color: #f44336; font-weight: bold;");
    } else if (status == "已支付") {
        ui->paymentButton->setVisible(false);
        ui->trackButton->setVisible(false);
        ui->confirmReceiptButton->setVisible(false);
        ui->cancelOrderButton->setVisible(true); // 可以取消订单
        ui->statusLabel->setStyleSheet("color: #f44336; font-weight: bold;");
    }
    else if (status == "已发货") {
        ui->paymentButton->setVisible(false);
        ui->trackButton->setVisible(false);
        ui->confirmReceiptButton->setVisible(true);
        ui->cancelOrderButton->setVisible(false); // 已发货不能取消
        ui->statusLabel->setStyleSheet("color: #ff9800; font-weight: bold;");
    } else if (status == "已完成") {
        ui->paymentButton->setVisible(false);
        ui->trackButton->setVisible(false);
        ui->confirmReceiptButton->setVisible(false);
        ui->cancelOrderButton->setVisible(false); // 已发货不能取消
        ui->statusLabel->setStyleSheet("color: #4CAF50; font-weight: bold;");
    } else if (status == "已取消") {
        ui->paymentButton->setVisible(false);
        ui->trackButton->setVisible(false);
        ui->confirmReceiptButton->setVisible(false);
        ui->cancelOrderButton->setVisible(false); // 已发货不能取消
        ui->statusLabel->setStyleSheet("color: #9e9e9e; font-weight: bold;");
    }
     qDebug() << "执行setOrderInfo函数";
}

// 收货信息
void orderStatusWidget::setShippingInfo(const QString &name,
                                      const QString &phone,
                                      const QString &address,
                                      const QString &logistics,
                                      const QString &trackingNumber)
{
    ui->recipientLabel->setText("收货人: " + name);
       ui->phoneLabel->setText("联系电话: " + phone);
       ui->addressLabel->setText("收货地址: " + address);
       ui->logisticsLabel->setText("物流公司: " + logistics);
       ui->trackingNumberLabel->setText("物流单号: " + trackingNumber);
       m_trackingNumber = trackingNumber;
}

// 价格信息
void orderStatusWidget::setPriceInfo(double subtotal,
                               double shippingFee,
                               double discount,
                               double total)
{
    ui->subtotalLabel->setText("商品总价: ¥" + QString::number(subtotal, 'f', 2));
    ui->shippingFeeLabel->setText("运费: ¥" + QString::number(shippingFee, 'f', 2));

    // 折扣显示处理
    QString discountText = (discount > 0) ?
        "-¥" + QString::number(discount, 'f', 2) :
        "¥0.00";
    ui->discountLabel->setText("优惠: " + discountText);

    ui->totalLabel->setText("实付款: ¥" + QString::number(total, 'f', 2));
    ui->totalLabel->setStyleSheet("font-weight: bold; color: #e91e63; font-size: 16px;");
     qDebug() << "执行setPriceInfo函数";
}

// 更新订单状态
void orderStatusWidget::updateOrderStatus(const QString &status)
{
    setOrderInfo(m_orderId, QDateTime::currentDateTime(), status, ui->paymentMethodLabel->text());
     qDebug() << "执行updateOrderStatus函数";
}

void orderStatusWidget::addProduct(const QString &name,
                             const QString &imageUrl,
                             double price,
                             int quantity)
{
    // 1. 商品项容器：极致紧凑布局
    QWidget *item = new QWidget(ui->productsContainer);
    item->setStyleSheet(R"(
        background-color: #f8f9fa;
        border-radius: 6px;
        padding: 4px; /* 极小内边距，内容贴边 */
        margin-bottom: 6px; /* 商品项间距适中 */
    )");

    // 2. 水平布局：图片 + 信息（紧凑间距）
    QHBoxLayout *itemLayout = new QHBoxLayout(item);
    itemLayout->setContentsMargins(0, 0, 0, 0); // 彻底去掉外层边距
    itemLayout->setSpacing(8); // 图片与信息的水平间距（可微调）

    // ---- 商品图片（无任何边框） ----
    QLabel *imageLabel = new QLabel(item);
    imageLabel->setFixedSize(80, 80); // 图片尺寸固定
    imageLabel->setStyleSheet(R"(
        qproperty-alignment: AlignCenter;
        /* 完全透明，无背景/边框 */
        background: transparent;
        border: none;
    )");

    // 加载图片（失败显示极简默认图）
    QString resourcePath = ":" + imageUrl;
     QPixmap pixmap(resourcePath);


    if (!pixmap.isNull()) {

        imageLabel->setPixmap(pixmap);
    } else {
        showDefaultImage(imageLabel); // 调用极简默认图
    }
    itemLayout->addWidget(imageLabel);

    // ---- 商品信息区域（垂直紧凑布局） ----
    QWidget *infoWidget = new QWidget(item);
    QVBoxLayout *infoLayout = new QVBoxLayout(infoWidget);
    infoLayout->setContentsMargins(0, 0, 0, 0); // 去掉信息内边距
    infoLayout->setSpacing(2); // 信息项垂直间距极小（可微调）

    // 第一行：商品名（加粗）
       QLabel *nameLabel = new QLabel(name, infoWidget);
       nameLabel->setStyleSheet(R"(
           font-weight: bold;
           color: #303133;
           font-size: 14px;
           margin: 0;
       )");
       nameLabel->setWordWrap(true);
       infoLayout->addWidget(nameLabel);

       // 第二行：单价（单独显示）
       QLabel *priceLabel = new QLabel(QString("单价: ¥%1").arg(price, 0, 'f', 2), infoWidget);
       priceLabel->setStyleSheet(R"(
           color: #606266;
           font-size: 13px;
           margin: 0;
       )");
       infoLayout->addWidget(priceLabel);

       // 第三行：数量（单独显示）
       QLabel *quantityLabel = new QLabel(QString("数量: × %1").arg(quantity), infoWidget);
       quantityLabel->setStyleSheet(R"(
           color: #606266;
           font-size: 13px;
           margin: 0;
       )");
       infoLayout->addWidget(quantityLabel);

    // 信息区域占满剩余空间（确保右侧对齐）
    itemLayout->addWidget(infoWidget, 1);

    // 3. 添加到主布局
    ui->productsLayout->addWidget(item);
    qDebug() << "执行 addProduct 函数";
}


// 极简默认图（无任何边框，纯文字提示）
void orderStatusWidget::showDefaultImage(QLabel *imageLabel)
{
    QPixmap defaultPixmap(80, 80);
    defaultPixmap.fill(Qt::transparent); // 完全透明背景

    QPainter painter(&defaultPixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(QColor(153, 153, 153)); // 浅灰色文字
    painter.setFont(QFont("Microsoft YaHei", 9, QFont::Normal));
    painter.drawText(defaultPixmap.rect(), Qt::AlignCenter, "无图片");

    imageLabel->setPixmap(defaultPixmap);
     qDebug() << "执行showDefaultImage函数";
}

 // 事件过滤器实现悬停效果
bool orderStatusWidget::eventFilter(QObject *obj, QEvent *event)
{
    // 只处理商品项容器的悬停事件
    for (int i = 0; i < ui->productsLayout->count(); i++) {
        QWidget *item = qobject_cast<QWidget*>(ui->productsLayout->itemAt(i)->widget());
        if (item && item == obj) {
            if (event->type() == QEvent::HoverEnter) {
                // 鼠标进入时设置悬停样式
                item->setStyleSheet(R"(
                    background-color: #f0f7ff;
                    border-radius: 10px;
                    padding: 15px;
                    margin-bottom: 15px;
                    border: 1px solid #91d5ff;
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                )");
            }
            else if (event->type() == QEvent::HoverLeave) {
                // 鼠标离开时恢复默认样式
                item->setStyleSheet(R"(
                    background-color: #ffffff;
                    border-radius: 10px;
                    padding: 15px;
                    margin-bottom: 15px;
                    border: 1px solid #e0e3e9;
                )");
            }
            break;
        }
    }
    return QWidget::eventFilter(obj, event);
     qDebug() << "执行eventFilterr函数";
}

void orderStatusWidget::clearProducts()
{
    // 清除现有内容
    QLayoutItem *child;
    while ((child = ui->productsLayout->takeAt(0)) != nullptr) {
        if (child->widget()) {
            delete child->widget();
        }
        delete child;
    }
    qDebug() << "执行clearProducts函数";
}

//点击支付按钮
void orderStatusWidget::on_paymentButton_clicked()
{
    // 创建支付页面
    paymentWidget *paymentDialog = new paymentWidget(this);

    // 从 UI 中提取总金额
        QString totalText = ui->totalLabel->text();
         m_totalAmount = totalText.split("¥").last().toDouble();
    // 设置订单信息
    paymentDialog->setOrderInfo(
        m_orderId,
        m_totalAmount,
        QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
    );

    // 设置二维码图片
    paymentDialog->setAlipayQrCode(":/icon/icon/支付宝.png");
    paymentDialog->setWechatQrCode(":/icon/icon/微信支付.png");

    // 连接支付成功信号
    connect(paymentDialog, &paymentWidget::paymentSuccess, this, [=](const QString &orderId, const QString &paymentMethod) {
        // 用户完成支付，更新数据库中订单状态
        QSqlQuery query;
        query.prepare("UPDATE Orders SET status='已支付'  WHERE order_id=:order_id");
        //query.bindValue(":payment_method", paymentMethod);
        query.bindValue(":order_id", orderId);

        if(query.exec()){
            // 更新界面状态
            updateOrderStatus("已支付");
            QMessageBox::information(this, "支付成功", "您的订单已成功支付！");
            emit paymentCompleted(orderId);
        }else{
            QMessageBox::critical(this, "错误", "更新订单状态失败:6666 " + query.lastError().text());
        }
    });

    // 显示支付对话框
    paymentDialog->exec();
    delete paymentDialog; // 释放资源
}

//点击物流跟踪按钮
void orderStatusWidget::on_trackButton_clicked()
{
    QMessageBox::information(this, "物流跟踪", "正在查询物流信息...");
    emit logisticsTrackRequested(m_trackingNumber);
}

//点击确认收货按钮
void orderStatusWidget::on_confirmReceiptButton_clicked()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认收货", "确定已经收到商品吗？",
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        QSqlQuery query;
        query.prepare("UPDATE Orders SET status='已完成' WHERE order_id=:order_id");
        query.bindValue(":order_id",m_orderId);

        if(query.exec()){
            //更新页面状态
            updateOrderStatus("已完成");
            //通知上层
            emit confirmReceiptRequested(m_orderId);
            QMessageBox::information(this, "成功", "已确认收货！");
        }else{
            QMessageBox::critical(this, "错误", "更新订单状态失败: " + query.lastError().text());
        }
    }
}

//点击取消订单按钮
void orderStatusWidget::on_cancelOrderButton_clicked()
{
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "取消订单", "确定要取消此订单吗？",
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        // 更新数据库中的订单状态
        QSqlQuery query;
        query.prepare("UPDATE Orders SET status = '已取消' "
                      "WHERE order_id = :order_id");
        query.bindValue(":order_id", m_orderId);

        if (query.exec()) {
            // 更新界面状态
            updateOrderStatus("已取消");

            QMessageBox::information(this, "成功", "订单已取消！");
        } else {
            QMessageBox::critical(this, "错误", "取消订单失败: " + query.lastError().text());
        }
    }
}

//支付成功后的操作
void orderStatusWidget::handlePaymentCompleted(const QString &orderId)
{
    // 这里编写处理支付完成后的代码
    qDebug() << "支付完成，订单号:" << orderId;
    qDebug() << "执行handlePaymentCompleted函数";



    // 或者：关闭当前窗口
    close();
}

void orderStatusWidget::initLayout() // 新增初始化布局函数，替代 addSeparators
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(20);
    mainLayout->setContentsMargins(20, 20, 20, 20);

    // 订单信息 + 收货信息（假设用 QGroupBox 包裹）
    QHBoxLayout *topLayout = new QHBoxLayout;
    topLayout->addWidget(ui->orderInfoGroupBox); // 订单信息组框
    topLayout->addWidget(ui->shippingInfoGroupBox); // 收货信息组框
    mainLayout->addLayout(topLayout);

    // 分割线 1（订单与商品之间）
    QFrame *line1 = new QFrame;
    line1->setFrameShape(QFrame::HLine);
    line1->setStyleSheet("background-color: #dcdfe6;");
    mainLayout->addWidget(line1);

    // 商品信息滚动区
    mainLayout->addWidget(ui->productsScrollArea);

    // 分割线 2（商品与价格之间）
    QFrame *line2 = new QFrame;
    line2->setFrameShape(QFrame::HLine);
    line2->setStyleSheet("background-color: #dcdfe6;");
    mainLayout->addWidget(line2);

    // 价格信息 + 操作按钮（假设用 QGroupBox 包裹）
    QVBoxLayout *bottomLayout = new QVBoxLayout;
    bottomLayout->addWidget(ui->priceInfoGroupBox); // 价格信息组框
    //bottomLayout->addWidget(ui->buttonBox); // 按钮组框
    mainLayout->addLayout(bottomLayout);

    setLayout(mainLayout);
    qDebug() << "执行initLayout函数";
}
